<script setup lang="ts" generic="T">
import { cloneDeep } from 'lodash-es'
// import Masonry from './masonry.vue'
import type { MasonryList, CarouselList } from './type'
import testData from './data'
import Content from './Content.vue'
// import { loadImage } from '~/components/global/MyWaterFall/utils'
// const datas = JSON.parse(JSON.stringify(testData))
// for (const key in datas) {
//   const elements = datas[key]
//   console.log('elements', elements)
//   elements.forEach(element => {
//     loadImage(element.src)
//       .then(image => {
//         element.width = image.width
//         element.height = image.height
//       })
//       .catch(() => {
//         element.width = 200
//         element.height = 200
//       })
//       .finally(() => {
//         console.log('datas', JSON.stringify(datas))
//       })
//   })
// }

const props = withDefaults(
  defineProps<{
    startPage?: number
  }>(),
  {
    startPage: 1
  }
)

const list = ref<MasonryList[]>([])

const imgs = [
  'http://gips3.baidu.com/it/u=1821127123,1149655687&fm=3028&app=3028&f=JPEG&fmt=auto?w=720&h=1280',
  'https://p2-kling.klingai.com/bs2/upload-ylab-stunt/437fe55e-d281-482b-bf7a-154486cec6e2-PoP3iUYbrvLwfaCbGPNxZw-output_ff.jpg?x-kcdn-pid=112452&x-oss-process=image%2Fresize%2Cw_360%2Ch_540%2Cm_mfit%2Fformat%2Cwebp',
  'https://p2-kling.klingai.com/bs2/upload-ylab-stunt/special-effect/output/HB1_PROD_ai_web_283777298265880/-286989576868890461/temp.jpg?x-kcdn-pid=112452&x-oss-process=image%2Fresize%2Cw_360%2Ch_630%2Cm_mfit%2Fformat%2Cwebp',
  'https://p2-kling.klingai.com/bs2/upload-ylab-stunt/036c0ae1-cee1-4731-a48c-ef8493d5d17a-cDWiDV3BCQuo8-HhREr90A-output_ff.jpg?x-kcdn-pid=112452&x-oss-process=image%2Fresize%2Cw_360%2Ch_203%2Cm_mfit%2Fformat%2Cwebp',
  'https://images.pexels.com/photos/2286895/pexels-photo-2286895.jpeg?cs=srgb&dl=pexels-rfera-2286895.jpg&fm=jpg',
  'http://gips0.baidu.com/it/u=3602773692,1512483864&fm=3028&app=3028&f=JPEG&fmt=auto?w=960&h=1280',
  'https://pic.chaopx.com/chao_origin_pic/24/01/08/92889bf42fbc3b1a3d5423912c8a5459.jpg!/fw/572/quality/90/unsharp/true/compress/true'
]

const carouselList: CarouselList[] = []
for (let index = 0; index < 5; index++) {
  carouselList.push({
    id: index,
    src: imgs[index % imgs.length]
  })
}

const loading = ref(false)
const finished = ref(false)
const error = ref(false)
const page = ref(props.startPage)

// 加载更多数据
const loadMore = async () => {
  if (loading.value || finished.value) return

  loading.value = true
  error.value = false

  try {
    // 模拟API请求
    await new Promise(resolve => setTimeout(resolve, 1000))

    // const count = list.value.length
    // for (let index = 0; index < 20; index++) {
    //   list.value.push({
    //     id: count + index,
    //     src: imgs[index % imgs.length]
    //   })
    // }
    list.value = list.value.concat(cloneDeep(testData[page.value]))
    page.value += 1
    // console.log(1111111111, testData, testData[page.value])

    // 模拟结束条件
    if (page.value >= 10) {
      finished.value = true
    }
  } catch (err) {
    error.value = true
    console.error('加载数据出错:', err)
  } finally {
    loading.value = false
  }
}
loadMore()

// 重试加载
const retryLoad = () => {
  error.value = false
  loadMore()
}
const { height: windowHeight } = useWindowSize()

const scrollContainer = ref()

onMounted(() => {
  scrollContainer.value = document.getElementById('main-container')?.parentElement
})
</script>

<template>
  <div
    ref="masonryRef"
    class="my-masonry"
  >
    <ScrollLoadMore
      :distance="150"
      :distance-from-bottom-load="windowHeight * 2"
      :error="error"
      :finished="finished"
      :loading="loading"
      @load="loadMore"
      @retry="retryLoad"
    >
      <MyWaterFall
        :left-top-params="{ columnNum: 2 }"
        :list="list"
        :scroll-container-id="scrollContainer"
      >
        <template #empty-space>
          <el-carousel class="carousel-container">
            <el-carousel-item
              v-for="carouse in carouselList"
              :key="carouse.id"
              class="carousel-item"
            >
              <img
                alt=""
                :src="carouse.src"
              />
            </el-carousel-item>
          </el-carousel>
        </template>
        <template #item="{ item, imgId }">
          <Content
            :img-id="imgId"
            :item="item"
            :type="item.type"
          />
        </template>
      </MyWaterFall>
      <template #finished>
        <div class="finished">没有更多了22</div>
      </template>
      <!-- <Masonry
        :carouse-list="carouselList"
        :list="list"
      /> -->
    </ScrollLoadMore>
  </div>
</template>

<style lang="less" scoped>
.my-masonry {
  .carousel-container {
    aspect-ratio: 592 / 240;

    :deep(.el-carousel__indicators) {
      bottom: 2px;
      right: 16px;
      left: auto;
      transform: none;

      .el-carousel__indicator {
        &.is-active {
          .el-carousel__button {
            background-color: #fff;
          }
        }

        .el-carousel__button {
          width: 5px;
          height: 5px;
          background: rgb(255 255 255 / 25%);
          box-shadow: 0 5.4px 13.5px 0 rgb(0 0 0 / 30%);
        }
      }
    }

    .carousel-item {
      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
    }
  }
}
</style>
